package com.common.base.tools.arouter

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.lifecycle.Lifecycle
import com.didi.drouter.api.DRouter
import com.didi.drouter.router.Request
import com.didi.drouter.router.Result
import com.didi.drouter.router.RouterCallback
import com.didi.drouter.store.RouterKey
import com.common.base.tools.utils.ApplicationUtils


fun startRouter(
    path: String?,
    bundle: Bundle? = null,
    callback: ((resultCode: Int, data: Intent?) -> Unit)? = null,
) {
    DRouterUtils.startAct(path, bundle, callback)
}

/**
 * 回调
 */
fun Activity.endRouter(intent: Intent){
    setResult(0X100086,intent)
    finish()
}

object DRouterUtils {
    fun startAct(
        path: String?,
        bundle: Bundle? = null,
        callback: ((resultCode: Int, data: Intent?) -> Unit)? = null,
    ) {
        DRouter.build(path)
            .putExtra("key", bundle) // 自定义参数
            .start(ApplicationUtils.context(), object : RouterCallback.ActivityCallback() {
                override fun onActivityResult(resultCode: Int, data: Intent?) {
                    callback?.invoke(resultCode, data)
                }
            })
    }

    /**
     * 事件
     * @param routerKey DRouterPath.DRouterKey
     * @param lifecycle 当前生命周期
     */
    fun register(routerKey: String, lifecycle: Lifecycle, callback: (Request, Result) -> Unit) {
        DRouter.register(
            RouterKey.build(routerKey).setLifecycle(lifecycle)
        ) { request, result ->
            callback.invoke(request, result)
        }
    }

//    fun navigation(pagePath: String?, key1: String?, value1: Int, key2: String?, value2: Int) {
//        DRouter.build(path) //                .putExtra(Extend.START_ACTIVITY_FLAGS, Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK)   // flag
//            .putExtra(
//                Extend.START_ACTIVITY_FLAGS,
//                Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
//            ) // flag
//            .putExtra("key", bundle) // 自定义参数
//            .start(context) { result -> val r = result.isActivityStarted }
//    }
}